const EggService = require('egg').Service
const ms = require('ms')
const dayjs = require('dayjs')
const jwt = require('jsonwebtoken')
const md5 = require('../utils/md5')
const ajv = require('../utils/ajv')

class Service extends EggService {
  // 登录
  async login(options, find) {
    const { ctx, config } = this
    const { SYSTEM_TYPE_STORE } = config.constant

    const { mobile, code, password, username, autoRegister } = options

    if (!find) {
      find = {}

      // 手机号 + 验证码
      if (code) {
        ajv(options, {
          required: ['mobile'],
        })

        // 验证短信码
        await this.service.sms.confirmCode({
          code,
          type: 0,
          mobile,
        })

        find = {
          mobile,
        }
      }
      // 手机号 + 密码
      else if (mobile) {
        ajv(options, {
          required: ['password'],
        })

        find = {
          mobile,
          password: md5(password),
        }
      }
      // 邮箱 + 密码
      else if (username && username.indexOf('@') != -1) {
        ajv(options, {
          required: ['password'],
        })

        find = {
          email: username,
          password: md5(password),
        }
      }
      // 账号 + 密码
      else if (username) {
        ajv(options, {
          required: ['password'],
        })

        find = {
          username,
          password: md5(password),
        }
      }
      // 刷新
      else {
        throw '请选择正确的登陆方式'
      }
    }

    let user = await ctx.model.User.findOne(find)

    const role = await ctx.model.AdminRole.findOne({
      roleName: '鉴定专家',
    })

    const admin = await ctx.model.Admin.findOne({
      mobile: user?.mobile,
      roleId: role?.id,
    })

    if (autoRegister && !user) {
      // 手机加验证码，自动注册
      if (mobile && code) {
        // 判断是否鉴定师
        user = await ctx.model.User.create({
          role: admin ? 1 : 0,
          mobile,
          isOpen: true,
          adminId: admin?.id,
        })
      }
    }

    if (!user) throw '登录失败'
    if (!user.isOpen) throw '账号已禁用'

    user.role = admin ? 1 : 0
    user.adminId = admin?.id
    user.loginTime = new Date()
    await user.save()

    // 用户信息
    const userInfo = {
      id: user._id,
      name: user.name,
      username: user.username,
      nickname: user.nickname,
      mobile: user.mobile,
      avatar: user.avatar,
      role: user.role,
    }

    // 签发token
    const token = jwt.sign(userInfo, config.jwt.secret + 'User', {
      expiresIn: config.jwt.expiresIn,
    })

    const exp = Date.now() + ms(config.jwt.expiresIn)

    return {
      user: userInfo,
      token,
      exp: parseInt(exp / 1000),
      expireTime: dayjs(exp).format('YYYY-MM-DD HH:mm:ss'),
    }
  }

  // 获取用户信息
  async getUserInfo(userId) {
    const { ctx } = this
    const { helper } = ctx

    const doc = await ctx.model.User.findOne({
      _id: userId,
    })

    if (!doc) throw '无效用户'

    const userInfo = helper.exclude(doc.toJSON(), ['password'])

    return userInfo
  }

  // 公众号登录
  async wechatMpLogin(wechat, callbackUrl) {
    const ydApi = new this.app.YdApi()

    const ydUser = await ydApi.getUserInfo(wechat.unionId)

    const { token } = await this.ydLogin(ydUser)

    if (!callbackUrl) callbackUrl = this.config.host + '/h5'
    else callbackUrl = decodeURIComponent(callbackUrl)

    if (callbackUrl.indexOf('?') == -1) callbackUrl += '?'
    else callbackUrl += '&'

    const url = callbackUrl + 'from=wx_mp&token=' + token

    console.log('登录成功', url)

    return url
  }

  // 云店用户登录
  // {
  //   memberId: 'd3223d8e-4d17-4b6e-a2bf-aae84daf4837',
  //   memberSeq: 'MEMBER2025146302',
  //   userName: '微信用户',
  //   nickName: '微信用户',
  //   memberType: 1,
  //   gradelevelId: '156c397b-3061-4de8-ae26-93a7ef18fb85',
  //   cellPhoneNo: '13880582267',
  //   sex: 0,
  //   gradeLevel: '普通会员',
  //   registerTime: null,
  //   wechatId: 'o5E7X6Vhvacj_lrvGe89HqPrBZ3I',
  //   openId: 'o7ZUs5LXOPviPEPCAzm-Y8BZqsa8',
  //   headPicUrl: 'https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132',
  //   currentBonuspoint: 0
  // }
  async ydLogin(ydUser) {
    const { ctx } = this

    if (!ydUser.cellPhoneNo) throw '请先绑定手机号'

    // 判断是否注册
    await ctx.model.User.findOneAndUpdate(
      {
        mobile: ydUser.cellPhoneNo,
      },
      {
        mobile: ydUser.cellPhoneNo,
        name: ydUser.userName,
        nickname: ydUser.nickName,
        avatar: ydUser.headPicUrl,
        isOpen: true,
      },
      {
        upsert: true, // 不存在插入
        setDefaultsOnInsert: true, // 允许插入默认值
      }
    )

    return await this.service.userAccount.login(
      {},
      {
        mobile: ydUser.cellPhoneNo,
      }
    )
  }
}

module.exports = Service
